{% extends "base.html" %}

{% block title %}日志{% endblock %}

{% block head %}
{{ super() }}
<link rel="stylesheet" href="/static/xterm/3.14.5/xterm.css"/>

{% endblock %}


{% block content %}
<!-- 页面头 -->
<!--<section class="content-header">-->
<!--  &lt;!&ndash;头部标题&ndash;&gt;-->
<!--  <h1>-->
<!--    日志-->
<!--    &lt;!&ndash;    <small>advanced tables</small>&ndash;&gt;-->
<!--  </h1>-->
<!--  &lt;!&ndash;面包屑&ndash;&gt;-->
<!--  <ol class="breadcrumb">-->
<!--    <li><a href="/"><i class="fa fa-home"></i> 主页</a></li>-->
<!--    <li><a href="/cluster">集群管理</a></li>-->
<!--    <li>工作负载</li>-->
<!--    <li>详情</li>-->
<!--    <li class="active">日志</li>-->
<!--  </ol>-->
<!--</section>-->

<!-- 页面内容 -->
<section class="content">
  <div class="row">
    <div class="col-xs-12">
      <div>
        <p>
          <span><b>日志</b></span>&nbsp;&nbsp;
          命名空间: <span id="namespace"></span>&nbsp;&nbsp;&nbsp;
          Pod: <span id="pod"></span>&nbsp;&nbsp;&nbsp;
          容器: <span id="container"></span>&nbsp;&nbsp;
          <button type="button" id="downloadBtn">下载日志</button>
          <button type="button" id="clearBtn">清屏</button>
          <button type="button" id="bottomBtn">跳到底部</button>
        </p>
      </div>
      <div id="terminal"></div>

    </div>
    <!-- /.col -->
  </div>
  <!-- /.row -->
</section>
<!-- /.页面内容 -->
{% endblock %}


{% block script %}
<script type="text/javascript" src="/static/xterm/3.14.5/xterm.js"></script>
<script type="text/javascript" src="/static/xterm/3.14.5/fit.js"></script>
<script>
    // 定义全局变量,用于下载
    var download_txt = ""

    // 下载日志的函数
    function download(filename, text) {
        var element = document.createElement('a');
        element.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(text));
        element.setAttribute('download', filename);
        element.style.display = 'none';
        document.body.appendChild(element);
        element.click();
        document.body.removeChild(element);
    }

    // 页面载入后执行
    $(function () {
        // 心跳总开关
        var ping_switch = true
        // 初始化xterm
        var term = new Terminal({
            fontSize: 15,
            fontFamily: 'courier',
            disableStdin: true,
            cursorBlink: false, // 关标闪烁
            cursorStyle: "underline", // 光标样式 'block' | 'underline' | 'bar'
            scrollback: 10000, // 当行的滚动超过初始值时保留的行视窗，越大回滚能看的内容越多，
        });
        term.open(document.getElementById('terminal'));

        // xterm 窗口自适应
        Terminal.applyAddon(fit);
        // 载入后 以及每次调整窗口大小后，同时调整日志消息框的大小
        $('#terminal').css('height', $(window).height() - 100)
        term.fit();
        $(window).resize(function () {
            $('#terminal').css('height', $(window).height() - 100)
            term.fit();
        })

        // 解析URL，获取参数，连接websocket服务器
        var pathName = window.document.location.pathname;
        var pathList = pathName.split("/")        // 例如 /cluster/ 被解析为 ['', 'cluster', '']
        console.log(pathList)
        var clusterid = pathList[3]
        var namespace = pathList[4]
        var pod = pathList[5]
        var container = pathList[6]
        var tail = "50"
        var follow = "true"
        $('#namespace').text(namespace)
        $('#pod').text(pod)
        $('#container').text(container)

        if (namespace == false) {
            namespace = "default"
        }
        if (namespace == false || pod == false) {
            alert("cannot get pod")
            return
        }
        url = "ws://" + document.location.host + "/ws/" + clusterid + "/" + namespace + "/" + pod + "/" + container + "/logs?"
        if (tail != false) {
            url = url + "&tail=" + tail
        }
        if (follow != false) {
            url = url + "&follow=" + follow
        }
        console.log(url);

        var conn = new WebSocket(url);

        conn.onopen = function (e) {
            // 保持心跳
            let a = 1;

            function ping() {
                // 如果总开关关闭，或者计数器大于60（半个小时）则关闭心跳
                if (!ping_switch || a > 60) return;
                console.log("发送心跳：", a++)
                msg = {operation: "stdin"}
                conn.send(JSON.stringify(msg))
                setTimeout(ping, 30000); // 每30秒发送心跳一次
            }

            ping();
        };
        conn.onmessage = function (event) {
            term.writeln(event.data)
            download_txt += event.data + "\r\n"
        };
        conn.onclose = function (event) {
            if (event.wasClean) {
                console.log(`[close] Connection closed cleanly, code=${event.code} reason=${event.reason}`);
            } else {
                console.log('[close] Connection died');
                term.writeln("")
            }
            term.write('Connection Reset By Peer! Try Refresh.');
            ping_switch = false;
        };

        conn.onerror = function (error) {
            console.log('[error] Connection error');
            term.write("error: " + error.message);
            term.destroy();
            ping_switch = false;
        };

        // 下载按钮
        $("#downloadBtn").click(function (event) {
            download("log.txt", download_txt);
        });

        // 清除按钮
        $("#clearBtn").click(function (event) {
            term.clear();
        });

        // 滚到底部按钮
        $("#bottomBtn").click(function (event) {
            term.scrollToBottom();
        });


    });
</script>
{% endblock %}